using System;
using System.Collections.Generic;
using System.Linq;
using ERPBackend.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;

namespace ERPBackend.Data
{
    public static class SeedData
    {
        public static void Initialize(IServiceProvider serviceProvider)
        {
            using (var context = new ApplicationDbContext(
                serviceProvider.GetRequiredService<DbContextOptions<ApplicationDbContext>>()))
            {
                // 如果数据库中已有数据，则不执行播种
                if (context.FirstLevelCategories.Any() ||
                    context.Roles.Any() ||
                    context.Suppliers.Any() ||
                    context.SecondLevelCategories.Any() ||
                    context.RolePermissions.Any() ||
                    context.SupplierContacts.Any() ||
                    context.SupplierQualifications.Any() ||
                    context.Materials.Any() ||
                    context.Departments.Any() ||
                    context.Users.Any() ||
                    context.UserRoles.Any() ||
                    context.Inventories.Any() ||
                    context.InventoryTransactions.Any())
                {
                    return;   // 数据库已包含数据
                }

                // 播种一级分类
                var firstLevelCategories = GenerateFirstLevelCategories(20);
                context.FirstLevelCategories.AddRange(firstLevelCategories);
                context.SaveChanges();

                // 播种角色
                var roles = GenerateRoles(20);
                context.Roles.AddRange(roles);
                context.SaveChanges();

                // 播种供应商
                var suppliers = GenerateSuppliers(20);
                context.Suppliers.AddRange(suppliers);
                context.SaveChanges();

                // 播种二级分类
                var secondLevelCategories = GenerateSecondLevelCategories(20, firstLevelCategories);
                context.SecondLevelCategories.AddRange(secondLevelCategories);
                context.SaveChanges();

                // 播种角色权限
                var rolePermissions = GenerateRolePermissions(20, roles);
                context.RolePermissions.AddRange(rolePermissions);
                context.SaveChanges();

                // 播种供应商联系人
                var supplierContacts = GenerateSupplierContacts(20, suppliers);
                context.SupplierContacts.AddRange(supplierContacts);
                context.SaveChanges();

                // 播种供应商资质
                var supplierQualifications = GenerateSupplierQualifications(20, suppliers);
                context.SupplierQualifications.AddRange(supplierQualifications);
                context.SaveChanges();

                // 播种物料
                var materials = GenerateMaterials(20, secondLevelCategories);
                context.Materials.AddRange(materials);
                context.SaveChanges();

                // 播种部门
                var departments = GenerateDepartments(20);
                context.Departments.AddRange(departments);
                context.SaveChanges();

                // 播种用户
                var users = GenerateUsers(20, departments);
                context.Users.AddRange(users);
                context.SaveChanges();

                // 更新部门经理
                UpdateDepartmentManagers(context, departments, users);
                context.SaveChanges();

                // 播种用户角色关系
                var userRoles = GenerateUserRoles(20, users, roles);
                context.UserRoles.AddRange(userRoles);
                context.SaveChanges();
            }
        }



        private static List<FirstLevelCategory> GenerateFirstLevelCategories(int count)
        {
            var categories = new List<FirstLevelCategory>();
            var random = new Random();
            var statuses = new byte[] { 0, 1 };
            var categoryNames = new[]
            {
                "电子设备", "机械配件", "化工原料", "纺织材料", "建筑材料",
                "办公用品", "包装材料", "五金工具", "塑料制品", "橡胶制品",
                "金属材料", "木材制品", "玻璃制品", "陶瓷制品", "皮革制品",
                "纸制品", "服装鞋帽", "体育用品", "医疗器械", "家具用品"
            };

            for (int i = 1; i <= count; i++)
            {
                categories.Add(new FirstLevelCategory
                {
                    CategoryCode = $"FLC{i:D3}",
                    CategoryName = categoryNames[i - 1],
                    Status = statuses[random.Next(statuses.Length)],
                    CreatedTime = DateTime.Now.AddDays(-random.Next(365)),
                    UpdatedTime = DateTime.Now
                });
            }

            return categories;
        }

        private static List<Role> GenerateRoles(int count)
        {
            var roles = new List<Role>();
            var random = new Random();
            var statuses = new bool[] { true, false };
            var roleNames = new[]
            {
                "管理员", "采购经理", "销售经理", "仓库管理员", "财务专员",
                "人力资源", "技术支持", "质量控制", "生产主管", "研发工程师",
                "物流专员", "市场专员", "客服代表", "项目经理", "数据分析师",
                "产品经理", "行政助理", "法务专员", "审计员", "培训师"
            };
            var descriptions = new[]
            {
                "系统管理员，拥有最高权限",
                "负责采购相关工作",
                "负责销售团队管理",
                "负责仓库物资管理",
                "负责财务相关工作",
                "负责人力资源管理",
                "提供技术支持服务",
                "负责质量控制工作",
                "负责生产部门管理",
                "负责研发项目",
                "负责物流配送工作",
                "负责市场推广工作",
                "负责客户服务工作",
                "负责项目管理工作",
                "负责数据分析工作",
                "负责产品管理工作",
                "负责行政事务工作",
                "负责法务相关工作",
                "负责审计相关工作",
                "负责员工培训工作"
            };

            for (int i = 1; i <= count; i++)
            {
                roles.Add(new Role
                {
                    RoleName = roleNames[i - 1],
                    Description = descriptions[i - 1],
                    Status = statuses[random.Next(statuses.Length)],
                    CreatedTime = DateTime.Now.AddDays(-random.Next(365)),
                    UpdatedTime = DateTime.Now
                });
            }

            return roles;
        }

        private static List<Supplier> GenerateSuppliers(int count)
        {
            var suppliers = new List<Supplier>();
            var random = new Random();
            var statuses = new byte[] { 0, 1 };
            var regions = new[] { "华东", "华南", "华北", "西南", "东北", "西北", "华中" };
            var types = new[] { "生产型", "贸易型", "服务型" };
            var levels = new[] { "一级", "二级", "三级" };
            var invoiceTypes = new[] { "增值税专用发票", "增值税普通发票", "电子发票" };

            for (int i = 1; i <= count; i++)
            {
                suppliers.Add(new Supplier
                {
                    SupplierCode = $"SUP{i:D3}",
                    SupplierName = $"供应商{i}",
                    SupplierShortName = $"供应{i}",
                    SupplierType = types[random.Next(types.Length)],
                    SupplierLevel = levels[random.Next(levels.Length)],
                    Address = $"{regions[random.Next(regions.Length)]}地区{random.Next(1000)}号",
                    TaxIdentificationNumber = $"91310000MA1{i:D3}XXXX",
                    BankNameAndAccount = $"中国工商银行 {random.Next(10000000, 99999999)}",
                    InvoiceType = invoiceTypes[random.Next(invoiceTypes.Length)],
                    InvoicingAddress = $"{regions[random.Next(regions.Length)]}地区{random.Next(1000)}号",
                    InvoicingPhone = $"021-{random.Next(10000000, 99999999)}",
                    Status = statuses[random.Next(statuses.Length)],
                    CreatedTime = DateTime.Now.AddDays(-random.Next(365)),
                    UpdatedTime = DateTime.Now
                });
            }

            return suppliers;
        }

        private static List<SecondLevelCategory> GenerateSecondLevelCategories(int count, List<FirstLevelCategory> firstLevelCategories)
        {
            var secondLevelCategories = new List<SecondLevelCategory>();
            var random = new Random();
            var statuses = new byte[] { 0, 1 };
            var categoryNames = new[]
            {
                "电脑配件", "手机配件", "网络设备", "办公设备", "安防设备",
                "汽车配件", "工业机械", "农业机械", "包装机械", "建筑机械",
                "有机化工", "无机化工", "精细化工", "化工原料", "化工产品",
                "棉纺织品", "麻纺织品", "毛纺织品", "丝纺织品", "化纤纺织品"
            };

            for (int i = 1; i <= count; i++)
            {
                var firstLevelCategory = firstLevelCategories[random.Next(firstLevelCategories.Count)];
                secondLevelCategories.Add(new SecondLevelCategory
                {
                    CategoryCode = $"SLC{i:D3}",
                    CategoryName = categoryNames[i - 1],
                    FirstLevelCategoryId = firstLevelCategory.Id,
                    Status = statuses[random.Next(statuses.Length)],
                    CreatedTime = DateTime.Now.AddDays(-random.Next(365)),
                    UpdatedTime = DateTime.Now
                });
            }

            return secondLevelCategories;
        }

        private static List<RolePermission> GenerateRolePermissions(int count, List<Role> roles)
        {
            var rolePermissions = new List<RolePermission>();
            var random = new Random();
            var permissions = new[] { "read", "write", "delete", "update", "admin" };
            var statuses = new bool[] { true, false };

            for (int i = 1; i <= count; i++)
            {
                var role = roles[random.Next(roles.Count)];
                rolePermissions.Add(new RolePermission
                {
                    RoleId = role.Id,
                    PermissionName = $"权限{i}",
                    Description = $"这是权限{i}的描述",
                    Status = statuses[random.Next(statuses.Length)],
                    CreatedTime = DateTime.Now.AddDays(-random.Next(365)),
                    UpdatedTime = DateTime.Now
                });
            }

            return rolePermissions;
        }

        private static List<SupplierContact> GenerateSupplierContacts(int count, List<Supplier> suppliers)
        {
            var supplierContacts = new List<SupplierContact>();
            var random = new Random();
            var contactTypes = new[] { "业务", "财务" };

            for (int i = 1; i <= count; i++)
            {
                var supplier = suppliers[random.Next(suppliers.Count)];
                supplierContacts.Add(new SupplierContact
                {
                    SupplierId = supplier.Id,
                    ContactType = contactTypes[random.Next(contactTypes.Length)],
                    ContactName = $"联系人{i}",
                    Phone = $"13900139{i:D3}",
                    Email = $"contact{i}@example.com",
                    Notes = $"联系人{i}的备注信息",
                    CreatedTime = DateTime.Now.AddDays(-random.Next(365)),
                    UpdatedTime = DateTime.Now
                });
            }

            return supplierContacts;
        }

        private static List<SupplierQualification> GenerateSupplierQualifications(int count, List<Supplier> suppliers)
        {
            var supplierQualifications = new List<SupplierQualification>();
            var random = new Random();
            var qualificationTypes = new[] { "营业执照", "生产许可证", "ISO认证", "质量认证", "环保认证" };

            for (int i = 1; i <= count; i++)
            {
                var supplier = suppliers[random.Next(suppliers.Count)];
                supplierQualifications.Add(new SupplierQualification
                {
                    SupplierId = supplier.Id,
                    QualificationType = qualificationTypes[random.Next(qualificationTypes.Length)],
                    FileName = $"资质文件{i}.pdf",
                    FilePath = $"/qualifications/supplier{i}.pdf",
                    UploadTime = DateTime.Now.AddDays(-random.Next(730)),
                    ValidUntil = DateTime.Now.AddDays(random.Next(730)),
                    Status = (byte)random.Next(0, 2),
                    CreatedTime = DateTime.Now.AddDays(-random.Next(365)),
                    UpdatedTime = DateTime.Now
                });
            }

            return supplierQualifications;
        }

        private static List<Material> GenerateMaterials(int count, List<SecondLevelCategory> secondLevelCategories)
        {
            var materials = new List<Material>();
            var random = new Random();
            var statuses = new byte[] { 0, 1 };

            for (int i = 1; i <= count; i++)
            {
                var secondLevelCategory = secondLevelCategories[random.Next(secondLevelCategories.Count)];
                materials.Add(new Material
                {
                    MaterialCode = $"MAT{i:D3}",
                    MaterialName = $"物料{i}",
                    Specification = $"规格{i}",
                    SecondLevelCategoryId = secondLevelCategory.Id,
                    Description = $"物料{i}的描述",
                    Status = statuses[random.Next(statuses.Length)],
                    CreatedTime = DateTime.Now.AddDays(-random.Next(365)),
                    UpdatedTime = DateTime.Now
                });
            }

            return materials;
        }

        private static List<Department> GenerateDepartments(int count)
        {
            var departments = new List<Department>();
            var random = new Random();
            var statuses = new bool[] { true, false };
            var departmentNames = new[]
            {
                "行政部", "人力资源部", "财务部", "销售部", "采购部",
                "生产部", "技术部", "研发部", "质量部", "仓库部",
                "物流部", "市场部", "客服部", "项目部", "数据部",
                "产品部", "法务部", "审计部", "培训部", "IT部"
            };

            for (int i = 1; i <= count; i++)
            {
                departments.Add(new Department
                {
                    // 使用BaseModel中的Id属性作为主键
                    DepartmentCode = $"DEP{i:D3}",
                    DepartmentName = departmentNames[i - 1],
                    ParentDepartmentId = i > 5 ? random.Next(1, 5) : null,
                    ManagerId = null, // 稍后更新
                    Description = $"{departmentNames[i - 1]}的描述",
                    Status = statuses[random.Next(statuses.Length)],
                    CreatedTime = DateTime.Now.AddDays(-random.Next(365)),
                    UpdatedTime = DateTime.Now
                });
            }

            return departments;
        }

        private static List<User> GenerateUsers(int count, List<Department> departments)
        {
            var users = new List<User>();
            var random = new Random();
            var statuses = new bool[] { true, false };
            var positions = new[] { "经理", "主管", "专员", "助理", "实习生" };
            var genders = new[] { "男", "女" };

            for (int i = 1; i <= count; i++)
            {
                var department = departments[random.Next(departments.Count)];
                users.Add(new User
                {
                    Username = $"user{i}",
                    Password = "password123", // 实际应用中应使用加密密码
                    Gender = genders[random.Next(genders.Length)],
                    DepartmentId = department.Id,
                    Position = positions[random.Next(positions.Length)],
                    Phone = $"13700137{i:D3}",
                    Email = $"user{i}@example.com",
                    HireDate = DateTime.Now.AddDays(-random.Next(730)),
                    Status = statuses[random.Next(statuses.Length)],
                    CreatedTime = DateTime.Now.AddDays(-random.Next(365)),
                    UpdatedTime = DateTime.Now
                });
            }

            return users;
        }

        private static void UpdateDepartmentManagers(ApplicationDbContext context, List<Department> departments, List<User> users)
        {
            var random = new Random();

            foreach (var department in departments)
            {
                // 为每个部门随机选择一个用户作为经理
                var manager = users[random.Next(users.Count)];
                department.ManagerId = manager.Id;
                context.Departments.Update(department);
            }
        }

        private static List<UserRole> GenerateUserRoles(int count, List<User> users, List<Role> roles)
        {
            var userRoles = new List<UserRole>();
            var random = new Random();

            // 确保每个用户至少有一个角色
            foreach (var user in users)
            {
                var role = roles[random.Next(roles.Count)];
                userRoles.Add(new UserRole
                {
                    UserId = user.Id,
                    RoleId = role.Id
                });
            }

            // 如果还需要更多角色关系
            for (int i = users.Count; i < count; i++)
            {
                var user = users[random.Next(users.Count)];
                var role = roles[random.Next(roles.Count)];
                // 避免重复的用户角色关系
                if (!userRoles.Any(ur => ur.UserId == user.Id && ur.RoleId == role.Id))
                {
                    userRoles.Add(new UserRole
                    {
                        UserId = user.Id,
                        RoleId = role.Id
                    });
                }
            }

            return userRoles;
        }
    }
}